package Service;

import Dao.KnowledgeBaseDAO;
import Dao.KnowledgeBaseMemberDAO;
import Dao.UserDAO;
import entity.KnowledgeBase;
import entity.KnowledgeBaseMember;
import entity.User;
import exception.BusinessException;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/5/1 16:28
 * @Version 1.0 （版本号）
 */
public class KnowledgeBaseService {
    private final KnowledgeBaseDAO knowledgeBaseDAO;
    private final KnowledgeBaseMemberDAO memberDAO;
    private final UserDAO userDAO;

    public KnowledgeBaseService(KnowledgeBaseDAO knowledgeBaseDAO,
                                KnowledgeBaseMemberDAO memberDAO,
                                UserDAO userDAO) {
        this.knowledgeBaseDAO = knowledgeBaseDAO;
        this.memberDAO = memberDAO;
        this.userDAO = userDAO;
    }

    /**
     * 创建知识库
     */
    public KnowledgeBase createKnowledgeBase(int creatorId, String name, String description, String accessLevel)
            throws SQLException, BusinessException {
        // 验证用户存在
        if (userDAO.getUserByUserId(creatorId) == null) {
            throw new BusinessException("用户不存在");
        }
//        System.out.println(creatorId + name + description + accessLevel);
        KnowledgeBase knowledgeBase = new KnowledgeBase();
        knowledgeBase.setName(name);
        knowledgeBase.setDescription(description);
        knowledgeBase.setCreatorId(creatorId);
        knowledgeBase.setAccessLevel(KnowledgeBase.AccessLevel.valueOf(accessLevel));

        return knowledgeBaseDAO.create(knowledgeBase);
    }

    /**
     * 更新知识库信息
     */
    public boolean updateKnowledgeBase(int knowledgeBaseId, int creatorId, String name,
                                       String description, String accessLevel)
            throws SQLException, BusinessException {
        // 验证知识库存在且属于该用户
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) {
            throw new BusinessException("知识库不存在");
        }
        if (kb.getCreatorId() != creatorId) {
            throw new BusinessException("无权修改此知识库");
        }

        kb.setName(name);
        kb.setDescription(description);
        kb.setAccessLevel(KnowledgeBase.AccessLevel.valueOf(accessLevel));

        return knowledgeBaseDAO.update(kb);
    }

    /**
     * 删除知识库
     */
    public boolean deleteKnowledgeBase(int knowledgeBaseId, int creatorId)
            throws SQLException, BusinessException {
        // 验证知识库存在且属于该用户
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) {
            throw new BusinessException("知识库不存在");
        }
        if (kb.getCreatorId() != creatorId) {
            throw new BusinessException("无权删除此知识库");
        }

        return knowledgeBaseDAO.delete(knowledgeBaseId, creatorId);
    }

    /**
     * 添加成员到知识库
     */
    public boolean addMember(int knowledgeBaseId, int creatorId, String userName, String role)
            throws SQLException, BusinessException {
        // 验证知识库存在且属于该用户
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) {
            throw new BusinessException("知识库不存在");
        }
        if (kb.getCreatorId() != creatorId) {
            throw new BusinessException("无权管理此知识库的成员");
        }

        // 验证目标用户存在
        User user = userDAO.getUserByUsername(userName);
        if (user == null) {
            throw new BusinessException("目标用户不存在");
        }

        // 检查是否已经是成员
        if (memberDAO.isMember(knowledgeBaseId, user.getUserId())) {
            throw new BusinessException("用户已是该知识库成员");
        }

        return memberDAO.addMember(knowledgeBaseId, user.getUserId(), role);
    }

    /**
     * 移除知识库成员
     */
    public boolean removeMember(int knowledgeBaseId, int creatorId, int userId)
            throws SQLException, BusinessException {
        // 验证知识库存在且属于该用户
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) {
            throw new BusinessException("知识库不存在");
        }
        if (kb.getCreatorId() != creatorId) {
            throw new BusinessException("无权管理此知识库的成员");
        }

        // 不能移除创建者
        if (kb.getCreatorId() == userId) {
            throw new BusinessException("不能移除知识库创建者");
        }

        return memberDAO.removeMember(knowledgeBaseId, userId);
    }

    /**
     * 获取用户的知识库列表
     */
    public List<KnowledgeBase> getUserKnowledgeBases(int userId) throws SQLException {
        return knowledgeBaseDAO.findAccessibleByUser(userId);
    }

    /**
     * 获取知识库成员列表
     */
    public List<KnowledgeBaseMember> getKnowledgeBaseMembers(int knowledgeBaseId, int requesterId)
            throws SQLException, BusinessException {
        // 验证请求者有权限访问该知识库
        if (!hasAccess(knowledgeBaseId, requesterId)) {
            throw new BusinessException("无权访问此知识库");
        }

        return memberDAO.listMembers(knowledgeBaseId);
    }

    /**
     * 检查用户是否有权限访问知识库
     */
    public boolean hasAccess(int knowledgeBaseId, int userId) throws SQLException {
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) return false;

        if (kb.getAccessLevel() == KnowledgeBase.AccessLevel.PUBLIC) {
            return true;
        }

        return kb.getCreatorId() == userId || memberDAO.isMember(knowledgeBaseId, userId);
    }

    /**
     * 获取单个知识库详情（带权限校验）
     */
    public KnowledgeBase getKnowledgeBase(int knowledgeBaseId, int userId)
            throws SQLException, BusinessException {

        // 1. 查询知识库基本信息
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) {
            throw new BusinessException("知识库不存在");
        }

        // 2. 检查访问权限
        if (!hasAccess(knowledgeBaseId, userId)) {
            throw new BusinessException("无权访问此知识库");
        }

        return kb;
    }
}